<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="elForm"
            size="small"
            :inline="true"
            style="margin-top: 10px"
            label-width="120px">
            
            <el-form-item label="设备mac："  prop="deviceMac">
                <el-input
                    v-model="queryParams.devMac"
                    placeholder="请输入插座编号"
                    clearable
                    :style="{ width: '100%' }"
                ></el-input>
            </el-form-item>

            <el-form-item label="时间段：" prop="timeType">
                <el-select v-model="queryParams.type" clearable placeholder="请选择" v-if="type === 'HOUR'">
                    <el-option
                        v-for="item in hourOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>

                <el-select v-model="queryParams.type" clearable placeholder="请选择" v-if="type === 'DAY'">
                    <el-option
                        v-for="item in dayOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="时间范围：" prop="searchTimeRange">
                <el-date-picker
                v-model="searchTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                 end-placeholder="结束时间"
                ></el-date-picker>
            </el-form-item>
                <el-button type="primary" style="margin-left: 10px" icon="el-icon-search" size="mini" @click="submitSearchForm">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetForm">重置</el-button>
                <el-button size="mini" @click="handleExport">导出历史数据</el-button>
            </el-form-item>
        </el-form>
        <!-- 图表 -->
        <el-row>
            <el-button-group>
                <el-button :type="hourBtnType" @click="queryHourCount">小时</el-button>
                <el-button :type="dayBtuType" @click="queryDayCount">天</el-button>
            </el-button-group>
            <div class="el-table el-table--enable-row-hover el-table--medium">
                <div ref="countCharts" style="height: 500px" />
            </div>
        </el-row>
        <!-- 表格 -->
        <el-row>
            <el-table :data="countInfo" stripe style="width: 100%" lazy height="250" border>

                <el-table-column label="设备MAC" prop="devMac" width="auto" align="center"></el-table-column>

                <el-table-column label="电压" prop="voltage" width="auto" align="center"></el-table-column>

                <el-table-column label="电流" prop="electric" width="auto" align="center"></el-table-column>

                <el-table-column label="功率" prop="power" width="auto" align="center"></el-table-column>

                <el-table-column label="功率因素" prop="powerFactor" width="auto" align="center"></el-table-column>

                <el-table-column label="频率" prop="frequency" width="auto" align="center"></el-table-column>

                <el-table-column label="累计能耗" prop="energy" width="auto" align="center"></el-table-column>

                <el-table-column label="发生时间" prop="createdTimeStr" width="auto" align="center"></el-table-column>

                <el-table-column label="正常数据量" prop="commonCount" width="auto" align="center"></el-table-column>

                <el-table-column label="异常数据量" prop="exceptionCount" width="auto" align="center"></el-table-column>

            </el-table>
        </el-row>

        <el-dialog title="导出历史数据(小时)" :visible.sync="uploadDialog" width="400px" append-to-body>

            <el-form ref="exportForm" :model="exportParam" label-width='120px'>

                <el-form-item label="设备MAC" prop="devMac">
                    <el-input v-model="exportParam.devMac" placeholder="请输入mac地址" clearable style="width: 240px"></el-input>
                </el-form-item>

                <el-form-item label="时间范围：" prop="exportTimeRange">
                    <el-date-picker
                        v-model="exportTimeRange"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                    ></el-date-picker>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exportData">导 出</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import { countByHour, countByDay } from '@/api/alm/statistics-charts/statistics-charts';
    import * as echarts from "echarts";

    export default {
        data() {
            return {
                type: 'HOUR',
                hourBtnType: 'primary',
                dayBtuType: 'info',
                queryParams: {},
                // 时间范围
                searchTimeRange: [],
                exportTimeRange: [],
                countInfo: null,
                countCharts: null,
                hourOptions: [{
                    value: 'EIGHT',
                    label: '最近8小时'
                    }, {
                    value: 'ONE_DAY',
                    label: '最近一天'
                    }, {
                    value: 'TWO_DAY',
                    label: '最近2天'
                    }
                ],
                dayOptions: [{
                    value: 'WEEK',
                    label: '最近一周'
                    }, {
                    value: 'A_MONTH',
                    label: '最近一个月'
                    }, {
                    value: 'TWO_MONTH',
                    label: '最近两个月'
                    }
                ],
                uploadDialog: false,
                exportParam: {},
            }
        },
        created() {

        },
        mounted() {},
        methods: {
            handleExport() {
                this.uploadDialog = true;
            },
            exportData() {
                this.exportParam.startTime = this.generateDateStr(this.exportTimeRange[0]);
                this.exportParam.endTime = this.generateDateStr(this.exportTimeRange[1]);
                console.log(this.exportParam);
                this.download(
                    "alm/count/export",
                    this.exportParam,
                    `导出历史数据.xlsx`
                )
            },

            submitSearchForm() {
                this.queryParams.startTime = this.generateDateStr(this.searchTimeRange[0]);
                this.queryParams.endTime = this.generateDateStr(this.searchTimeRange[1]);
                console.log(this.queryParams);
                if(this.type == 'HOUR') {
                    // 查询小时维度统计数据
                    countByHour(this.queryParams).then(res => {
                        this.countInfo = res.data;
                        console.log(res);
                        // 生成图表
                        this.generateCharts();
                    })
                }else if(this.type == 'DAY') {
                    // 查询天维度统计数据
                    countByDay(this.queryParams).then(res => {
                        this.countInfo = res.data;
                        console.log(res);
                        // 生成图表
                        this.generateCharts();
                    })
                }else{
                    this.$message.error("统计维度选择错误...");
                }
                
            },
            generateCharts() {
                if (!echarts.getInstanceByDom(this.$refs.countCharts)) {
                    this.countCharts = echarts.init(this.$refs.countCharts, "macarons");
                }
                let opt = {
                    title: {
                        text: " ",
                        subtext: "",
                    },
                    tooltip: {
                        trigger: "axis",
                    },
                    legend: {
                        data: ["电压", "电流", "功率", "功率因数", "用电量"],
                    },
                    grid: {
                        left: "3%",
                        right: "4%",
                        bottom: "3%",
                        containLabel: true,
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {},
                        },
                    },
                    xAxis: {
                        type: "category",
                        boundaryGap: false,
                        // data: ['18:01:23', '18:21:23', '18:31:23', '18:41:23', '18:51:23', '18:54:23', '18:56:23']
                        data: [],
                    },
                    yAxis: {
                        type: "value",
                    },
                    series: [
                        {
                            name: "电压",
                            type: "line",
                            data: [],
                            itemStyle: {
                                normal: {
                                    color: '#607bca', //改变折线点的颜色
                                    lineStyle: {
                                        color: '#607bca' //改变折线颜色
                                    }
                                }
                            },
                        },
                        {
                            name: "电流",
                            type: "line",
                            data: [],
                            itemStyle: {
                                normal: {
                                    color: '#93cd77', //改变折线点的颜色
                                    lineStyle: {
                                        color: '#93cd77' //改变折线颜色
                                    }
                                }
                            },
                        },
                        {
                            name: "功率",
                            type: "line",
                            data: [],
                            itemStyle: {
                                normal: {
                                    color: '#fac859', //改变折线点的颜色
                                    lineStyle: {
                                        color: '#fac859' //改变折线颜色
                                    }
                                }
                            },
                        },
                        {
                            name: "功率因数",
                            type: "line",
                            data: [],
                            itemStyle: {
                                normal: {
                                    color: '#ee6a6a', //改变折线点的颜色
                                    lineStyle: {
                                        color: '#ee6a6a' //改变折线颜色
                                    }
                                }
                            },
                        },
                        {
                            name: "用电量",
                            type: "line",
                            data: [],
                            itemStyle: {
                                normal: {
                                    color: '#73c0de', //改变折线点的颜色
                                    lineStyle: {
                                        color: '#73c0de' //改变折线颜色
                                    }
                                }
                            }, 
                        }
                    ],
                };

                console.log("this.countInfo ", this.countInfo);

                let i = 0;
                for (let info of this.countInfo) {
                    opt.series[0].data.push(info.voltage);
                    opt.series[1].data.push(info.electric);
                    opt.series[2].data.push(info.power);
                    opt.series[3].data.push(info.powerFactor);
                    opt.series[4].data.push(info.energy);
                    var time = info.createdTimeStr;
                    opt.xAxis.data.push(time);
                    opt.title.subtext = info.devMac.toUpperCase();
                }
                this.countCharts.setOption(opt);
                window.addEventListener("resize", () => {
                    this.countCharts.resize();
                });
            },
            resetForm() {
                this.queryParams = {};
                console.log(this.queryParams);
            },

            queryHourCount(){
                // 页面变化
                this.type = 'HOUR';
                this.hourBtnType = 'primary';
                this.dayBtuType = 'info';
                this.queryParams.type = '';
            },
            queryDayCount(){
                // 页面变化
                this.type = 'DAY';
                this.hourBtnType = 'info';
                this.dayBtuType = 'primary';
                this.queryParams.type = '';
            },

            // 生成时间字符串，格式为 yyyy-MM-dd HH:mm:ss
            generateDateStr(timestamp) {
                if(timestamp != undefined && timestamp != null && timestamp != ''){
                    var date = new Date(timestamp);
                    var year = date.getFullYear();
                    var month = date.getMonth() + 1;
                    var strDate = date.getDate();
                    var hour = date.getHours();
                    var minute = date.getMinutes();
                    var second = date.getSeconds();
                    month = month > 9 ? month : '0' + month
                    strDate = strDate > 9 ? strDate : '0' + strDate
                    hour = hour > 9 ? hour : '0' + hour
                    minute = minute > 9 ? minute : '0' + minute
                    second = second > 9 ? second : '0' + second
                    if(this.type == 'HOUR') {
                        return year + '-' + month + '-' + strDate + ' ' + hour
                    }
                    if(this.type == 'DAY') {
                        return year + '-' + month + '-' + strDate
                    }
                    
                }
                return '';
            }
        }
    }
</script>